<?php
$table_source = $old_nav_db_config['DB_PREFIX'].'goods';
$table_site = $old_nav_db_config['DB_PREFIX'].'site';
$table_target = $db_config['DB_PREFIX'].'goods';
$table_key = $db_config['DB_PREFIX'].'goods_key';
$table_match = $db_config['DB_PREFIX'].'goods_match';
$isnow = isset($_REQUEST['isnow']) ? intval($_REQUEST['isnow']) : 0;
$tindex = isset($_REQUEST['tindex']) ? intval($_REQUEST['tindex']) : 0;
$tindex = max($tindex,0);

$timezone = fanweDBC('TIME_ZONE');

if(function_exists('date_default_timezone_set'))
	@date_default_timezone_set('Etc/GMT'.($timezone > 0 ? '-' : '+').(abs($timezone)));

$now_time = time() - date('Z');

if($isnow == 0)
{
    $date = $db_source->query("SELECT MIN(end_time) AS num FROM $table_source WHERE end_time >= ".str2Time('2009-01-01 00:00:00'));

    if($date)
    {
        $date = $date[0]['num'];
		$min_year = toDate($date,'Y');
		$min_month = toDate($date,'m');
		$max_year = toDate($now_time,'Y');
		$max_month = toDate($now_time,'m');
		$time_arr = array();

        for($year = $min_year;$year <= $max_year;$year++)
		{
			$mmonth = 12;
			$month = 1;

			if($year == $max_year)
				$mmonth = $max_month;

			if($year == $min_year)
				$month = $min_month;

			for($month;$month <= $mmonth;$month++)
			{
				$next_year = $year;
				$next_month = $month + 1;

				if($month == 12)
				{
					$next_year++;
					$next_month = 1;
				}

				$time_arr[] = str2Time($next_year.'-'.$next_month.'-01 00:00:00');
			}
		}
    }
    else
    {
        $min_year = toDate($now_time,'Y');
        $min_month = toDate($now_time,'m');
        $max_year = toDate($now_time,'Y');
        $max_month = toDate($now_time,'m');
        if($max_month == 12)
        {
            $max_year++;
            $max_month=1;
        }
        $time_arr[] = str2Time($max_year.'-'.$max_month.'-01 00:00:00');
    }

    if($tindex < count($time_arr))
    {
        if($begin == 0 && $tindex == 0)
        {
            $db_source->query("UPDATE $table_source SET city = '全国' WHERE city = ''");
            $is_partition = $db_target->query("SHOW VARIABLES LIKE 'have_partitioning'");
            if($is_partition && strtolower($is_partition[0]['Value']) == 'yes')
            {
                $index = 1;
                $sql = 'ALTER TABLE '.$table_key.' PARTITION BY RANGE(end_time)(';
                foreach($time_arr as $time)
                {
                    $sql .= "PARTITION p$index VALUES LESS THAN ($time),";
                    $index++;
                }
                $sql .= "PARTITION p$index VALUES LESS THAN MAXVALUE)";
                //$db_target->query($sql);
            }
            else
            {
                showjsmessage("跳过团购商品分区优化功能，分区功能需要MYSQL 5.1以上，并开启表分区功能",1);
            }
        }

        $max_time = $time_arr[$tindex];
        $min_time = 0;
        if($tindex > 0)
            $min_time = $time_arr[$tindex - 1];

        $where = "";
        if($min_time == 0)
            $min_time = str2Time($min_year.'-'.$min_month.'-01 00:00:00');

        $where = " AND end_time >= $min_time AND end_time < $max_time";

        $data_num = $db_source->query('SELECT COUNT(*) AS num FROM '.$table_source.' WHERE status = 1'.$where);

        if(count($data_num) > 0)
            $data_num = $data_num[0]['num'];
        else
            $data_num = 0;

        if($data_num > $begin)
        {
            $limit = $data_num - $begin;
            if($limit > 1000)
                $limit = 1000;

            $data_list = $db_source->query("SELECT g.id,g.site_id,g.name,g.city,g.cate_id,g.url,g.click_count,g.best_count,g.collect_count,g.shop_price,g.market_price,g.end_time,g.brief,g.status,g.sort,g.small_img,g.big_img,g.add_time,g.is_best,g.content,g.bought,g.collect_key,g.collect_url,g.collect_name,s.name as site_name 
                FROM $table_source AS g 
                LEFT JOIN $table_site AS s ON s.id = g.site_id 
                WHERE g.status = 1 $where LIMIT ".$begin.','.$limit);

            showjsmessage("开始转换数据表 goods ".toDate($min_time,'Y年m月')."数据 $begin 到 ".($begin + $limit)." 行");

            $data_count = count($data_list);
            $data = $data_list[0];
            $fields = array_keys($data);
            $start_sql = "INSERT INTO $table_target ( `" . implode('`, `', $fields) . '` ) VALUES ';

            for($j=0; $j< $data_count; $j++)
            {
                $data = $data_list[$j];
                $data['small_img'] = preg_replace("/^\/Public/", '/public', $data['small_img']);
                $data['big_img'] = preg_replace("/^\/Public/", '/public', $data['big_img']);
                $record = array_map('dumpEscapeString', $data);
                $sql = $start_sql . ' ('. implodeInsertValues($record) .')';
				
                $db_target->query($sql);
				
				$db_target->query('INSERT INTO '.$table_match.' (id,content) VALUES('.$data['id'].',\''.segmentToUnicode(clearSymbol($data['site_name'].$data['name'])).'\')');
            }

            showjsmessage("转换数据表 goods ".toDate($min_time,'Y年m月')."数据　goods $begin 到 ".($begin + $limit)." 行  成功");

            if($limit < 1000)
                $tindex++;
            else
            {
                showjsmessage(U('Index/convert',array('table'=>'goods','tindex'=>$tindex,'begin'=>$begin + $limit)),5);
                exit;
            }
        }
        else
            $tindex++;
    }
}

if($tindex >= count($time_arr))
{
	$db_target->query("INSERT INTO $table_key SELECT id, site_id, city, cate_id, sort, r_sort, cr_sort,0,0,0,0,end_time FROM $table_target");

	showjsmessage("转换数据表　goods ... 成功");
	showjsmessage(U('Index/convert',array('table'=>'goods_bond','begin'=>0)),5);
    exit;
}
else
{
    showjsmessage(U('Index/convert',array('table'=>'goods','tindex'=>$tindex,'begin'=>$begin + $limit)),5);
    exit;
}

/**
 * utf8字符转Unicode字符
 * @param string $char 要转换的单字符
 * @return void
 */
function utf8ToUnicode($char)
{
	switch(strlen($char))
	{
		case 1:
			return ord($char);
		case 2:
			$n = (ord($char[0]) & 0x3f) << 6;
			$n += ord($char[1]) & 0x3f;
			return $n;
		case 3:
			$n = (ord($char[0]) & 0x1f) << 12;
			$n += (ord($char[1]) & 0x3f) << 6;
			$n += ord($char[2]) & 0x3f;
			return $n;
		case 4:
			$n = (ord($char[0]) & 0x0f) << 18;
			$n += (ord($char[1]) & 0x3f) << 12;
			$n += (ord($char[2]) & 0x3f) << 6;
			$n += ord($char[3]) & 0x3f;
			return $n;
	}
}

/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @param string $pre
 * @return string
 */
function segmentToUnicode($str,$pre = '')
{
	$arr = array();
	$str_len = mb_strlen($str,'UTF-8');
	for($i = 0;$i < $str_len;$i++)
	{
		$s = mb_substr($str,$i,1,'UTF-8');
		if($s != ' ' && $s != '　')
		{
			$arr[] = $pre.'ux'.utf8ToUnicode($s);
		}
	}

	$arr = array_unique($arr);

	return implode(' ',$arr);
}

/**
 * 清除符号
 * @param string $str 要清除符号的字符串
 * @return string
 */
function clearSymbol($str)
{
	static $symbols = NULL;
	if($symbols === NULL)
	{
		$symbols = file_get_contents(ROOT_PATH.'./public/table/symbol.table');
		$symbols = explode("\r\n",$symbols);
	}

	return str_replace($symbols,"",$str);
}
?>